package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.ExpressQueryDto;
import com.yami.shop.bean.enums.FaceDesignOrderStatusEnum;
import com.yami.shop.bean.enums.FaceDesignPayStatusEnum;
import com.yami.shop.bean.enums.FaceDesignPayTypeEnum;
import com.yami.shop.bean.model.FaceDesignOrder;
import com.yami.shop.bean.model.FaceDraft;
import com.yami.shop.bean.model.FaceDesign;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.ExpressQueryParam;
import com.yami.shop.bean.param.FaceDesignOrderParam;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.FaceDesignOrderMapper;
import com.yami.shop.service.*;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 人脸设计稿订单服务实现类
 * @author AI Assistant
 */
@Service
public class FaceDesignOrderServiceImpl extends ServiceImpl<FaceDesignOrderMapper, FaceDesignOrder> implements FaceDesignOrderService {

    private final FaceDesignOrderMapper faceDesignOrderMapper;
    private final Express100Service express100Service;
    private final FaceDesignService faceDesignService;
    private final UserService userService;

    @Autowired
    @Lazy
    private FaceDraftService faceDraftService;

    @Override
    public IPage<FaceDesignOrder> pageByUserId(PageParam<FaceDesignOrder> page, String userId, Integer orderStatus) {
        LambdaQueryWrapper<FaceDesignOrder> queryWrapper = new LambdaQueryWrapper<FaceDesignOrder>()
                .eq(FaceDesignOrder::getUserId, userId)
                .eq(orderStatus != null, FaceDesignOrder::getOrderStatus, orderStatus)
                .orderByDesc(FaceDesignOrder::getCreateTime);
        return this.page(page, queryWrapper);
    }

    @Override
    public FaceDesignOrder getByOrderNumber(String orderNumber) {
        FaceDesignOrder order = this.getOne(new LambdaQueryWrapper<FaceDesignOrder>().eq(FaceDesignOrder::getOrderNumber, orderNumber));
        if (order != null) {
            // 填充关联字段
            fillRelatedFields(order);
        }
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FaceDesignOrder createOrder(String userId, Long designId, Long draftId, BigDecimal orderAmount) {
        FaceDesignOrder order = new FaceDesignOrder();
        order.setUserId(userId);
        order.setDesignId(designId);
        order.setDraftId(draftId);
        order.setOrderAmount(orderAmount);
        order.setActualAmount(orderAmount);
        order.setOrderStatus(FaceDesignOrderStatusEnum.WAITING_PAY.getValue());
        order.setPayStatus(FaceDesignPayStatusEnum.UNPAID.getValue());
        order.setOrderNumber(generateOrderNumber());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        this.save(order);
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(FaceDesignOrder order) {
        // 生成订单编号
        order.setOrderNumber(generateOrderNumber());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        // 设置默认状态
        if (order.getOrderStatus() == null) {
            order.setOrderStatus(FaceDesignOrderStatusEnum.WAITING_SCHEDULE.getValue());
        }
        if (order.getPayStatus() == null) {
            order.setPayStatus(FaceDesignPayStatusEnum.UNPAID.getValue());
        }

        this.save(order);
        return order.getOrderNumber();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applySchedule(String orderNumber, String userId) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 检查订单状态是否为待排单
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.WAITING_SCHEDULE.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.WAITING_CONFIRM_SCHEDULE.getValue());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmSchedule(String orderNumber) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null) {
            return false;
        }

        // 检查订单状态是否为待确认排单
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.WAITING_CONFIRM_SCHEDULE.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.WAITING_PAY.getValue());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(String orderNumber, Integer payType, String payNo) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.WAITING_PAY.getValue())) {
            throw new RuntimeException("订单状态异常，无法支付");
        }

        // 微信支付逻辑
        if (payType == 1) {
            // 微信支付：保持订单状态为待支付，支付状态为未支付
            order.setOrderStatus(FaceDesignOrderStatusEnum.WAITING_PAY.getValue());
            order.setPayStatus(FaceDesignPayStatusEnum.UNPAID.getValue());
            order.setPayType(payType);
            order.setPayNo(payNo);
            // 不设置支付时间，等待微信回调
        } else {
            // 其他支付方式：直接设置为已支付
            order.setOrderStatus(FaceDesignOrderStatusEnum.PAID.getValue());
            order.setPayStatus(FaceDesignPayStatusEnum.PAID.getValue());
            order.setPayType(payType);
            order.setPayNo(payNo);
            order.setPayTime(new Date());
        }

        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean shipOrder(String orderNumber, String trackingNumber, String expressCompany) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null) {
            return false;
        }

        // 检查订单状态是否为已支付
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.PAID.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.SHIPPED.getValue());
        order.setTrackingNumber(trackingNumber);
        order.setExpressCompany(expressCompany);
        order.setShipTime(new Date());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReceive(String orderNumber, String userId) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 检查订单状态是否为已发货
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.SHIPPED.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.COMPLETED.getValue());
        order.setReceiveTime(new Date());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(String orderNumber, String userId, String cancelReason) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 检查订单状态是否允许取消（待排单、待确认排单、待支付状态可以取消）
        Integer orderStatus = order.getOrderStatus();
        if (!orderStatus.equals(FaceDesignOrderStatusEnum.WAITING_SCHEDULE.getValue()) &&
            !orderStatus.equals(FaceDesignOrderStatusEnum.WAITING_CONFIRM_SCHEDULE.getValue()) &&
            !orderStatus.equals(FaceDesignOrderStatusEnum.WAITING_PAY.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.CANCELLED.getValue());
        order.setCancelReason(cancelReason);
        order.setCancelTime(new Date());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applyRefund(String orderNumber, String userId, String refundReason) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 检查订单状态是否允许退款（已支付、已发货状态可以申请退款）
        Integer orderStatus = order.getOrderStatus();
        if (!orderStatus.equals(FaceDesignOrderStatusEnum.PAID.getValue()) &&
            !orderStatus.equals(FaceDesignOrderStatusEnum.SHIPPED.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.REFUNDING.getValue());
        order.setPayStatus(FaceDesignPayStatusEnum.REFUNDING.getValue());
        order.setRefundReason(refundReason);
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmRefund(String orderNumber) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null) {
            return false;
        }

        // 检查订单状态是否为退款中
        if (!order.getOrderStatus().equals(FaceDesignOrderStatusEnum.REFUNDING.getValue())) {
            return false;
        }

        order.setOrderStatus(FaceDesignOrderStatusEnum.REFUNDED.getValue());
        order.setPayStatus(FaceDesignPayStatusEnum.REFUNDED.getValue());
        order.setRefundTime(new Date());
        order.setUpdateTime(new Date());
        return this.updateById(order);
    }

    @Override
    public IPage<FaceDesignOrder> pageByOrderParam(PageParam<FaceDesignOrder> page, FaceDesignOrderParam orderParam) {
        LambdaQueryWrapper<FaceDesignOrder> queryWrapper = buildQueryWrapper(orderParam);
        queryWrapper.orderByDesc(FaceDesignOrder::getCreateTime);
        IPage<FaceDesignOrder> result = this.page(page, queryWrapper);

        // 填充关联字段
        if (result.getRecords() != null) {
            for (FaceDesignOrder order : result.getRecords()) {
                fillRelatedFields(order);
            }
        }

        return result;
    }

    @Override
    public List<FaceDesignOrder> listByOrderParam(FaceDesignOrderParam orderParam) {
        LambdaQueryWrapper<FaceDesignOrder> queryWrapper = buildQueryWrapper(orderParam);
        queryWrapper.orderByDesc(FaceDesignOrder::getCreateTime);
        List<FaceDesignOrder> result = this.list(queryWrapper);

        // 填充关联字段
        if (result != null) {
            for (FaceDesignOrder order : result) {
                fillRelatedFields(order);
            }
        }

        return result;
    }

    /**
     * 构建查询条件包装器
     */
    private LambdaQueryWrapper<FaceDesignOrder> buildQueryWrapper(FaceDesignOrderParam orderParam) {
        LambdaQueryWrapper<FaceDesignOrder> queryWrapper = new LambdaQueryWrapper<>();

        if (orderParam != null) {
            queryWrapper.eq(StrUtil.isNotBlank(orderParam.getUserId()), FaceDesignOrder::getUserId, orderParam.getUserId())
                       .eq(StrUtil.isNotBlank(orderParam.getOrderNumber()), FaceDesignOrder::getOrderNumber, orderParam.getOrderNumber())
                       .eq(orderParam.getStatus() != null, FaceDesignOrder::getOrderStatus, orderParam.getStatus())
                       .eq(orderParam.getPayStatus() != null, FaceDesignOrder::getPayStatus, orderParam.getPayStatus())
                       .eq(orderParam.getDesignId() != null, FaceDesignOrder::getDesignId, orderParam.getDesignId())
                       .eq(orderParam.getDraftId() != null, FaceDesignOrder::getDraftId, orderParam.getDraftId())
                       .eq(StrUtil.isNotBlank(orderParam.getReceiverName()), FaceDesignOrder::getReceiverName, orderParam.getReceiverName())
                       .eq(StrUtil.isNotBlank(orderParam.getReceiverPhone()), FaceDesignOrder::getReceiverPhone, orderParam.getReceiverPhone())
                       .eq(StrUtil.isNotBlank(orderParam.getExpressCompany()), FaceDesignOrder::getExpressCompany, orderParam.getExpressCompany())
                       .eq(StrUtil.isNotBlank(orderParam.getExpressNumber()), FaceDesignOrder::getTrackingNumber, orderParam.getExpressNumber());

            // 时间范围查询
            if (orderParam.getStartTime() != null && orderParam.getEndTime() != null) {
                queryWrapper.between(FaceDesignOrder::getCreateTime, orderParam.getStartTime(), orderParam.getEndTime());
            } else if (orderParam.getStartTime() != null) {
                queryWrapper.ge(FaceDesignOrder::getCreateTime, orderParam.getStartTime());
            } else if (orderParam.getEndTime() != null) {
                queryWrapper.le(FaceDesignOrder::getCreateTime, orderParam.getEndTime());
            }
        }

        return queryWrapper;
    }

    @Override
    public FaceDesignOrder getByDesignId(Long designId) {
        return this.getOne(new LambdaQueryWrapper<FaceDesignOrder>().eq(FaceDesignOrder::getDesignId, designId));
    }

    @Override
    public OrderStatistics getOrderStatistics(String userId) {
        OrderStatistics statistics = new OrderStatistics();

        // 总订单数
        long totalOrders = this.count(new LambdaQueryWrapper<FaceDesignOrder>().eq(FaceDesignOrder::getUserId, userId));
        statistics.setTotalOrders((int) totalOrders);

        // 待支付订单数
        long waitingPayOrders = this.count(new LambdaQueryWrapper<FaceDesignOrder>()
                .eq(FaceDesignOrder::getUserId, userId)
                .eq(FaceDesignOrder::getOrderStatus, FaceDesignOrderStatusEnum.WAITING_PAY.getValue()));
        statistics.setWaitingPayOrders((int) waitingPayOrders);

        // 待发货订单数
        long waitingShipOrders = this.count(new LambdaQueryWrapper<FaceDesignOrder>()
                .eq(FaceDesignOrder::getUserId, userId)
                .eq(FaceDesignOrder::getOrderStatus, FaceDesignOrderStatusEnum.PAID.getValue()));
        statistics.setWaitingShipOrders((int) waitingShipOrders);

        // 已发货订单数
        long shippedOrders = this.count(new LambdaQueryWrapper<FaceDesignOrder>()
                .eq(FaceDesignOrder::getUserId, userId)
                .eq(FaceDesignOrder::getOrderStatus, FaceDesignOrderStatusEnum.SHIPPED.getValue()));
        statistics.setShippedOrders((int) shippedOrders);

        // 已完成订单数
        long completedOrders = this.count(new LambdaQueryWrapper<FaceDesignOrder>()
                .eq(FaceDesignOrder::getUserId, userId)
                .eq(FaceDesignOrder::getOrderStatus, FaceDesignOrderStatusEnum.COMPLETED.getValue()));
        statistics.setCompletedOrders((int) completedOrders);

        return statistics;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNumber() {
        return "FD" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }

    @Override
    public Object getExpressStatus(String orderNumber) {
        FaceDesignOrder order = getByOrderNumber(orderNumber);
        if (order == null) {
            return null;
        }

        // 检查订单是否有快递信息
        if (StrUtil.isBlank(order.getExpressCompany()) || StrUtil.isBlank(order.getTrackingNumber())) {
            return "暂无快递信息";
        }

        // 调用快递100 API查询物流状态
        ExpressQueryParam param = new ExpressQueryParam();
        param.setExpressCompanyCode(order.getExpressCompany());
        param.setExpressNumber(order.getTrackingNumber());

        try {
            ExpressQueryDto expressInfo = express100Service.queryExpress(param);
            return expressInfo != null ? expressInfo.getExpressStatus() : "查询失败";
        } catch (Exception e) {
            return "快递查询异常";
        }
    }

    /**
     * 填充订单关联字段
     */
    private void fillRelatedFields(FaceDesignOrder order) {
        if (order.getDraftId() != null) {
            // 查询并设置草稿信息
            FaceDraft faceDraft = faceDraftService.getById(order.getDraftId());
            order.setFaceDraft(faceDraft);
        }

        if (order.getDesignId() != null) {
            // 查询并设置设计稿信息
            FaceDesign faceDesign = faceDesignService.getById(order.getDesignId());
            order.setFaceDesign(faceDesign);
        }

        if (order.getUserId() != null) {
            // 查询并设置用户信息
            User user = userService.getById(order.getUserId());
            order.setUser(user);
        }
    }

    public FaceDesignOrderServiceImpl(FaceDesignOrderMapper faceDesignOrderMapper,
                                    Express100Service express100Service,
                                    FaceDesignService faceDesignService,
                                    UserService userService) {
        this.faceDesignOrderMapper = faceDesignOrderMapper;
        this.express100Service = express100Service;
        this.faceDesignService = faceDesignService;
        this.userService = userService;
    }
}
